package com.dhcc.android.base.gis;


import com.dhcc.android.base.utils.datamanager.bussiness.WholeTask;

import org.dom4j.DocumentException;

import java.io.File;
import java.io.IOException;
import java.util.List;

import srs.DataSource.DataTable.DataRow;
import srs.DataSource.DataTable.DataTable;
import srs.DataSource.Table.ITable;
import srs.DataSource.Vector.ShapeFileClass;
import srs.Geometry.Envelope;
import srs.Geometry.IEnvelope;
import srs.Geometry.IGeometry;
import srs.Geometry.IPoint;
import srs.Layer.IFeatureLayer;
import srs.Layer.ILayer;
import srs.Map.IMap;
import srs.Utility.sRSException;

/**
 * 任务包数据管理，这里仅仅是IMAGE、TASK中数据的管理， 建议把数据管理都写在一个类，如有需要可以考虑用单利，
 * 
 * @author lzy
 * @version 20150530
 */
public class DataController {
	public static String intolayer;

	//
	/**
	 * 一定是引用srs.Map.IMap，你们mapcontrol里的map
	 * 
	 */
	private IMap mMap;

	/**
	 * TASK中的layer们
	 * 
	 */
	private WholeTask mTASK = null;
	/**
	 * IMAGE中的layer们
	 * 
	 */
	private WholeTask mIMAGE = null;

	/**
	 * 底图图层个数
	 * 
	 */
	private int countOfImageLayers;

	private static DataController DATACONTROLL = null;

	private DataController() {
	}

	public static DataController getInstance() {
		if (DATACONTROLL == null) {
			DATACONTROLL = new DataController();
		}
		return DATACONTROLL;
	}

	public int getCountOfImageLayers() {
		return countOfImageLayers;
	}

	public void setCountOfImageLayers(int countOfImageLayers) {
		this.countOfImageLayers = countOfImageLayers;
	}

	public IMap getmMap() {
		return mMap;
	}

	public void setmMap(IMap mMap) {
		this.mMap = mMap;
	}

	public WholeTask getmTASK() {
		return mTASK;
	}

	public void setmTASK(WholeTask mTASK) {
		this.mTASK = mTASK;
	}

	public WholeTask getmIMAGE() {
		return mIMAGE;
	}

	public void setmIMAGE(WholeTask mIMAGE) {
		this.mIMAGE = mIMAGE;
	}

	public void loadDataController(String IMAGPATH, String TASKPATH) {

		File file = new File(TASKPATH);
		if (file.exists()
				&& TASKPATH.substring(TASKPATH.indexOf(".")).equalsIgnoreCase(
						".TCF")) {
			mTASK = new WholeTask();
			try {
				mTASK.LoadFromFile(TASKPATH);
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}

		file = new File(IMAGPATH);
		if (file.exists()
				&& IMAGPATH.substring(IMAGPATH.indexOf(".")).equalsIgnoreCase(
						".TCF")) {
			mIMAGE = new WholeTask();
			try {
				mIMAGE.LoadFromFile(IMAGPATH);
				countOfImageLayers = mIMAGE.getLayersCount();
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 添加底图tcf
	 * 
	 * @throws IOException
	 */
	public void AddImage() throws IOException {
		loadMap(true, mIMAGE);
//		loadMap(false, mTASK);
	}

	/**
	 * 添加TASK中的tcf，在image基础上添加新图层；
	 *
	 * @param startindex
	 *            从第几个图层开始添加任务图层,一般用countOfImageLayers就够了
	 * @return 是否成功
	 * @throws IOException
	 * @throws sRSException
	 */
	public boolean addTask(int startindex) throws Exception {
		// 清楚startindx开始的所有图层；从“分选项卡”页面回到选样本页面时，需要清除d调查layer
		// while(mMap.GetLayer(startindex)!=null){
		// mMap.RemoveLayer(startindex);
		// }

		loadMap(false, mTASK);
		return true;
	}

	/**
	 * @throws IOException
	 *             向Imap中添加“tcf”图层组
	 * @param task
	 *            tcf图层组
	 * @param isClear
	 *            是否要清除原有图层
	 * @throws
	 */
	private void loadMap(boolean isClear, WholeTask task) throws IOException {
		if (isClear)
			mMap.ClearLayer();
		if (task == null)
			return;
		int count = task.getLayersCount();
		for (int i = 0; i < count; i++) {
			ILayer layer = task.GetLayer(i);
			if (layer != null && layer.getVisible()) {
				mMap.AddLayer(layer);
			}
		}
	}

	/**
	 * 
	 * @param layerName
	 *            指定layerName
	 * @param index
	 *            顺序号
	 */

	public void loadMapById(String layerName, int index) {
		ILayer clayer = mTASK.GetLayer(layerName);
		if (clayer instanceof IFeatureLayer) {
			IFeatureLayer targetLayer = (IFeatureLayer) clayer;
			// goe为空间信息。
			IGeometry geo;
			try {
				// index为选中记录在shp文件中的顺序号，注意：是“顺序号”，不是现实的那个“编号”。
				geo = targetLayer.getFeatureClass().getGeometry(index);
				IPoint centerPoint = geo.CenterPoint();// 中心点
				IEnvelope cEnv = geo.Extent();// 外包矩形，即范围
				// 屏幕范围
				cEnv = new Envelope(cEnv.XMin() - cEnv.Width() * 2 / 3,
						cEnv.YMin() - cEnv.Height() * 2 / 3, cEnv.XMax()
						+ cEnv.Width() * 2 / 3, cEnv.YMax()
						+ cEnv.Height() * 2 / 3);
				mMap.setExtent(cEnv);

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 显示某层Layer（如样本单位区）的某些对象（选中对象）。
	 * 层级的跳转根据task中的TASK.xml文件的level，读取相应layer的name属性
	 * 
	 * @param layername
	 *            操作图层的NAME属性
	 * @param indexsOfSelected
	 *            显示那些对象。 重点：indexOfSelected有两种情况
	 *            1.所有对象都显示，indexsOfSelected为null。如：村、3km网格
	 *            2.仅仅显示选中的，indexsOfSelected为选中对象的“顺序号”。如：样本单位区、300m样本
	 * @throws IOException
	 * @throws sRSException
	 */
	public ILayer setActiveLayer(String layername,
			List<Integer> indexsOfSelected/*, boolean continueAdd*/)
					throws sRSException, IOException {
		// 去掉非IMAGE中的图层
		/*removed by 李忠义 20150814
		 * if (!continueAdd) {
			if (mMap.getLayerCount() > countOfImageLayers) {
				mMap.RemoveLayer(countOfImageLayers);
			}
		}*/

		IFeatureLayer targetlayer = (IFeatureLayer) mTASK.GetLayer(layername);

		/*edit by 李忠义 
		 * 20150814 
		 * 避免增添重复的layer*/
		if(!mMap.getLayers().contains(targetlayer)){
			mMap.AddLayer(targetlayer);
		}
		targetlayer.setSelectionOfDisplay(indexsOfSelected);
		return targetlayer;
	}

	/**
	 * 获取图层
	 * 
	 * @param layername
	 *            图层名
	 * @return
	 */
	public IFeatureLayer getLayer(String layername) {
		IFeatureLayer targetlayer = (IFeatureLayer) mTASK.GetLayer(layername);
		return targetlayer;
	}

	/**
	 * add 杨宗仁
	 * 
	 * 判断该地块是否进行过，属性填报，如进行过则字段COMPLETE值为1，否则为1
	 * 
	 * @param DKID
	 *            传入参数为地块唯一表示
	 */
	public void isComplete(String DKID) {
		IFeatureLayer targetlayer = (IFeatureLayer) mTASK.GetLayer(intolayer);
		String sql = "ID=" + DKID;
		DataTable table = ((ITable) targetlayer.getFeatureClass())
				.getAttributeTable();
		List<Integer> integers;
		try {
			integers = table.Select(sql);
			DataRow row = table.getEntityRows().get(integers.get(0));
			if (!row.getString("COMPLETE").equals("2")) {
				row.setInt("COMPLETE", 2);
				row.mState = 1;
				((ShapeFileClass) targetlayer.getFeatureClass()).DBFChangeOngly = true;
				((ShapeFileClass) targetlayer.getFeatureClass()).SaveEdit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
